package cn.tedu.ivos.geofence.service.impl;

import cn.tedu.ivos.base.exception.ServiceException;
import cn.tedu.ivos.base.response.StatusCode;
import cn.tedu.ivos.geofence.mapper.GeofenceMapper;
import cn.tedu.ivos.geofence.pojo.dto.GeofenceParam;
import cn.tedu.ivos.geofence.pojo.dto.GeofenceQuery;
import cn.tedu.ivos.geofence.pojo.entity.Geofence;
import cn.tedu.ivos.geofence.pojo.vo.GeofenceVO;
import cn.tedu.ivos.geofence.service.GeofenceService;
import cn.tedu.ivos.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleQuery;
import cn.tedu.ivos.vehicle.pojo.vo.VehicleVO;
import cn.tedu.ivos.vehicle.service.VehicleService;
import lombok.Data;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class GeofenceServiceImpl implements GeofenceService {
    @Autowired
    private GeofenceMapper geofenceMapper;
    @Autowired
    private VehicleMapper vehicleMapper;
    @Override
    public List<GeofenceVO> selectGeofence(GeofenceQuery geofenceQuery) {
        log.info("开始执行查询电子围栏的业务层方法");
       List<GeofenceVO> list = geofenceMapper.selectGeofence(geofenceQuery);
        return list;
    }

    @Override
    public void saveGeofence(GeofenceParam geofenceParam) {
        log.info("开始执行保存电子围栏的业务层方法");
        Geofence geofence = new Geofence();
        BeanUtils.copyProperties(geofenceParam,geofence);
        if(geofence.getId() == null){//新增
            geofence.setCreateTime(new Date());
            geofence.setStatus("1");
            geofenceMapper.insert(geofence);
        }else {//修改
            geofence.setUpdateTime(new Date());
            geofenceMapper.update(geofence);
        }
    }

    @Override
    public void deleteGeo(Long id) {
        log.info("开始执行删除围栏业务");
        //业务：需要判断当前围栏上是否有已绑定车辆，如果有绑定车辆就不能删除
        //1.封装车辆查询的DTO对象VehicleQuery
        VehicleQuery vehicleQuery = new VehicleQuery();
        vehicleQuery.setGeofenceId(id);
        //2.调用车辆数据层查询是否绑定在当前围栏上的车辆信息
        List<VehicleVO> list = vehicleMapper.selectVehicle(vehicleQuery);
        //3.判断list是否为空
        if(list.size() > 0 && list != null){
            throw new ServiceException(StatusCode.OPERATION_FAILED);
        }else {
            log.info("围栏上没有绑定车辆，可以删除");
            geofenceMapper.deleteGeoById(id);
        }
    }
}
